﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;

namespace SimpleRest.Core.Extensions
{
    public static class ValidationUtility
    {
        public static void RecursiveValidation(object obj)
        {
            if (obj == null) return;
            Type objType = obj.GetType();

            ValidationContext context = new ValidationContext(obj, null, null);
            Validator.ValidateObject(obj, context, true);

            if (objType.GetInterface(typeof(System.Collections.IEnumerable).FullName) != null)
            {
                foreach (object item in obj as System.Collections.IEnumerable)
                    RecursiveValidation(item);
            }
            else
            {
                foreach (var prop in objType.GetProperties())
                {
                    if (!SimpleRest.Serialization.TypeCache.PrimitiveTypes.Contains(prop.PropertyType) && prop.GetCustomAttributes(true).FirstOrDefault(d => d is ValidationAttribute) != null)
                    {
                        RecursiveValidation(prop.GetValue(obj, null));
                    }
                }
            }
        }
    }
}
